#include <stdio.h>
#include <stdlib.h>
#include "save_wav.h"

void
save_wav(char* name, long size, smpl_t* buf, short channels, long rate) {
        FILE *file;
        if ((file = fopen(name, "wb")) == NULL) {
                printf("Cannot open file\n");
                return;
        }

        char riff[4] = {'R', 'I', 'F', 'F'};
        long buf_len = size * sizeof(smpl_t) ;
        long totalpacklen = 36 + buf_len;
        char wavefmt[8] = {'W', 'A', 'V', 'E', 'f', 'm', 't', ' '};
        long fmtchunklen = 0x10;
        short zeroone = 0x01;
        //short mono = channels;
        long s_rate = (long) rate;
        long bps = s_rate * channels * sizeof(smpl_t);
        short bpsample = sizeof(smpl_t) * channels;
        short bitpsample = bpsample * 8;
        char data[4] = {'d', 'a', 't', 'a'};

        fwrite(riff, 1, 4, file);
        fwrite(&totalpacklen, 4, 1, file);
        fwrite(wavefmt, 1, 8, file);
        fwrite(&fmtchunklen, 4, 1, file);
        fwrite(&zeroone, 2, 1, file);
        fwrite(&channels, 2, 1, file);
        fwrite(&s_rate, 4, 1, file);
        fwrite(&bps, 4, 1, file);
        fwrite(&bpsample, 2, 1, file);
        fwrite(&bitpsample, 2, 1, file);
        fwrite(data, 1, 4, file);
        fwrite(&buf_len, 4, 1, file);
        fwrite(buf, sizeof(smpl_t), size, file);

        fclose(file);
}
